import json
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.urls import reverse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.utils.decorators import method_decorator
from web import models
from web.forms.manage import WikiModelForm
from utils.tencent.cos import CosBucket
from utils.encrypt import uid


class Wiki(View):

    def get(self, request, project_id):
        wiki_id = request.GET.get('wiki_id')
        if wiki_id and not wiki_id.isdecimal():
            return render(request, 'wiki.html')

        wiki_object = models.Wiki.objects.filter(id=wiki_id, project=request.tracer.project.id).first()
        return render(request, 'wiki.html', {'wiki_object': wiki_object})


class WikiAdd(View):

    def get(self, request, project_id):
        form = WikiModelForm(request)
        return render(request, 'wiki_form.html', {'form': form, 'title': '新建文章'})

    def post(self, request, project_id):
        form = WikiModelForm(request, data=request.POST)
        if form.is_valid():
            # 判断用户是否选择父文章
            if form.instance.parent:  # models对象
                form.instance.depth = form.instance.parent.depth + 1
            else:
                form.instance.depth = 1

            form.instance.project = request.tracer.project  # project_id

            form.save()

            return redirect(reverse('wiki', kwargs={'project_id': project_id}) + '?wiki_id=' + str(form.instance.id))

        return render(request, 'wiki_form.html', {'form': form})


@method_decorator(csrf_exempt, name="dispatch")
class WikiCatalog(View):

    def get(self, request, project_id):
        """ wiki目录"""

        data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').order_by(
            'depth', 'id')
        return JsonResponse({'status': True, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    rdstr = request.GET.get('rdstr')
    if rdstr != request.tracer.rdstr:
        return JsonResponse({'status': False, 'error': '状态异常'})
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return JsonResponse({'status': True, 'text': '删除成功！'})


def wiki_edit(request, project_id, wiki_id):
    """ 编辑文章 """
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    if not wiki_id:
        return redirect(reverse('wiki', kwargs={'project_id': project_id}))

    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form, 'title': '编辑文章'})

    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 判断用户是否选择父文章
        if form.instance.parent:  # models对象
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project  # project_id
        form.save()
        return redirect(reverse('wiki', kwargs={'project_id': project_id}) + '?wiki_id=' + str(form.instance.id))
    return render(request, 'wiki_form.html', {'form': form})


@xframe_options_sameorigin
@csrf_exempt
def wiki_upload(request, project_id):
    """ markdown 上传图片 """
    print("yeyeyeye!!")
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    file_object = request.FILES.get('editormd-image-file')
    if not file_object:
        result['message'] = '文件不存在'
        return JsonResponse(result)

    ext = file_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.tracer.user.phone), ext)

    # 实例化桶对象
    cos = CosBucket(request.tracer.project.region)
    # 上传文件
    # 桶， 文件对象， 文件名
    file_url = cos.upload_bucket_from_buffer(
        bucket=request.tracer.project.bucket,
        file_object=file_object,
        key=key
    )
    print(file_url)
    # markdown成功显示
    result['success'] = 1
    result['url'] = file_url
    return JsonResponse(result)
